package thread;

/**
 * Created by fanzhenyu02 on 2020/7/3.
 */
public class AlternateThread {
    public static int count = 0;
    public static Object object = new Object();
    public static final int loop = 10;


    public static void main(String[] arg) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < loop; i++) {
                        synchronized (object) {
                            object.notify();
                            object.wait();
                        }
                        count++;
                        System.out.println("t1 " + count);
                    }
                    synchronized (object) {
                        object.notify();
                    }
                } catch (Throwable e) {
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < loop; i++) {
                        synchronized (object) {
                            object.notify();
                            object.wait();
                        }
                        count++;
                        System.out.println("t2 " + count);
                    }
                    synchronized (object) {
                        object.notify();
                    }
                } catch (Throwable e) {
                }
            }
        });
        t1.start();
        t2.start();


        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        System.out.println("count: " + count);
    }
}
